package com.echo.im.client.facade;

import com.echo.im.client.handler.message.MessageHandler;
import com.echo.im.client.handler.message.MessageHandlerFactory;
import com.echo.im.client.helper.OnlineStatusHelper;
import com.echo.im.client.handler.platform.PlatformCmdHandler;
import com.echo.im.common.enums.IMTerminalType;
import com.echo.im.common.model.BaseMessage;
import com.echo.im.common.model.platform.PlatformCmd;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 *
 * 对外提供统一抽象
 * @author lxy
 * @date 2024-08-14
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class IMClient{

    private final MessageHandlerFactory messageHandlerFactory;
    private final OnlineStatusHelper onlineStatusHelper;
    private final List<PlatformCmdHandler> platformCmdHandlerList;

    @Value("${spring.application.name}")
    private String appName;

    public <T extends BaseMessage<?>> void sendMessage(T message) {
        @SuppressWarnings("unchecked")
        MessageHandler<T> handler = (MessageHandler<T>) messageHandlerFactory.getHandler((Class<? extends BaseMessage<?>>) message.getClass());
        if (handler != null) {
            handler.handleMessage(message);
        } else {
            log.warn("No message handler found for message type: {}", message.getClass());
        }
    }

    /**
     * 判断用户是否在线
     *
     * @param userId 用户id
     */
    public Boolean isUserOnline(Long userId){
        return onlineStatusHelper.isUserOnline(userId);
    }

    /**
     * 判断多个用户是否在线
     *
     * @param userIds 用户id列表
     * @return 在线的用户列表
     */
    public List<Long> getOnlineUser(List<Long> userIds){
        return onlineStatusHelper.getOnlineUser(userIds);
    }


    /**
     * 判断多个用户是否在线
     *
     * @param userIds 用户id列表
     * @return 在线的用户终端
     */
    public Map<Long,List<IMTerminalType>> getOnlineTerminal(List<Long> userIds){
        return onlineStatusHelper.getOnlineTerminal(userIds);
    }

    public void handleAndSendPlatformCmd(PlatformCmd platformCmd) {
        log.info("Handling platform command: {}", platformCmd);
        // 处理平台命令的逻辑
        for (PlatformCmdHandler<PlatformCmd> handler : platformCmdHandlerList) {
            if (handler.support(platformCmd)) {
                handler.sendPlatformCmd(platformCmd);
                break;
            }
        }
    }

}
